package com.ciei.dpagm.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ciei.dpagm.common.enums.RelationalOperatorEnum;
import com.ciei.dpagm.common.service.BaseService;
import com.ciei.dpagm.entity.Condition;
import com.ciei.dpagm.mapper.ConditionMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

/**
 * @author pp
 * @date 2023/03/10
 */
@Service
public class ConditionService extends BaseService<ConditionMapper, Condition> {

    /**
     * 根据规则集id列表获取条件列表
     * @param ruleSetIdList
     * @return
     */
    public List<Condition> getListByRuleSetIdList(List<Integer> ruleSetIdList){
        if(ruleSetIdList.isEmpty()){
            return new ArrayList<>();
        }
        LambdaQueryWrapper<Condition> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Condition::getRuleSetId,ruleSetIdList)
                .orderByAsc(Condition::getOrderId);
        return list(lambdaQueryWrapper);
    }

    /**
     * 根据规则id列表获取条件列表
     * @param ruleIdList
     * @return
     */
    public List<Condition> getListByRuleIdList(List<Integer> ruleIdList){
        if(ruleIdList.isEmpty()){
            return new ArrayList<>();
        }
        LambdaQueryWrapper<Condition> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Condition::getRuleId,ruleIdList)
                .orderByAsc(Condition::getOrderId);
        return list(lambdaQueryWrapper);
    }

    /**
     * 根据规则集id获取条件列表
     * @param ruleSetId
     * @return
     */
    public List<Condition> getListByRuleSetId(Integer ruleSetId){
        LambdaQueryWrapper<Condition> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Condition::getRuleSetId,ruleSetId)
                .orderByAsc(Condition::getOrderId);
        return list(lambdaQueryWrapper);
    }

    /**
     * 根据规则集id列表删除
     * @param ruleSetIdList
     */
    public void removeByRuleSetIdList(List<Integer> ruleSetIdList){
        if(ruleSetIdList.isEmpty()){
            return;
        }
        LambdaQueryWrapper<Condition> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Condition::getRuleSetId,ruleSetIdList);
        remove(lambdaQueryWrapper);
    }

    /**
     * 获取逻辑运算符Pattern
     * @return
     */
    public Pattern getRelationalOperatorPattern(){
        List<String> relationalOperatorList = RelationalOperatorEnum.getOperatorList();
        String relationalOperatorJoin = StringUtils.join(relationalOperatorList, "|");
        String pattern = String.format("([a-zA-Z0-9_]+)(?%s)", relationalOperatorJoin);
        Pattern relationalOperatorPattern = Pattern.compile(pattern);
        return relationalOperatorPattern;
    }
}
